package com.ruoyi.common.utils.bean;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ObjectMapConverter {

    public static void main(String[] args) throws  Exception{
        Person person = new Person();
        person.setName("Alice");
        person.setAge(30);
        person.setCreateTime(new Date());

        Map<String, Object> personMap = ObjectMapConverter.objectToMap(person);
        System.out.println(personMap);  // 输出：{name=Alice, age=30}

        Map<String, Object> personMap1 = new HashMap<>();
        personMap1.put("name","zyc");
        personMap1.put("age",34);
        personMap1.put("createTime",new Date());
        Person newPerson = ObjectMapConverter.mapToObject(personMap1, Person.class);
        System.out.println(newPerson.getName());  // 输出：Alice
        System.out.println(newPerson.getCreateTime());  // 输出：Alice
    }

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        T obj = clazz.newInstance();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Field field = null;
            try {
                field = clazz.getDeclaredField(entry.getKey());
                field.setAccessible(true);
                field.set(obj, entry.getValue());
            } catch (NoSuchFieldException ignored) {
            }
        }
        return obj;
    }
}

